package org.example.project.common.error.util;

import org.aspectj.lang.JoinPoint;
import org.example.project.common.error.enums.ErrorCode;
import org.example.project.common.util.AspectLogUtils;
import org.example.project.common.error.exception.BizCustomException;
import org.example.project.common.error.exception.DaoException;
import org.example.project.common.error.exception.ServiceException;
import org.slf4j.Logger;

/**
 * @author wenxy
 * @date 2020/11/6
 */
public class ErrorHandleUtils {

    public static void handleThirdException(JoinPoint joinPoint, Throwable e, Logger log) {
        // 兼容自定义业务异常
        if (e instanceof BizCustomException) {
            return;
        }

        //  自定义Dao异常(手动抛出，记录请求信息、简单异常信息),日志级别warn
        if (log.isWarnEnabled() && e instanceof DaoException) {
            log.warn(AspectLogUtils.buildLog(joinPoint, e.getMessage()).toString());
            return;
        }

        // 程序调用运行异常，记录请求信息、异常堆栈信息，日志级别error,封装DaoException重新抛出
        if (log.isErrorEnabled()) {
            log.error(AspectLogUtils.buildLog(joinPoint, e).toString());
            throw new DaoException(ErrorCode.C0001, e);
        }
    }

    public static void handleServiceException(JoinPoint joinPoint, Throwable e, Logger log) {
        // 兼容自定义异常(手动抛出，记录请求信息、简单异常信息),日志级别warn
        if (e instanceof BizCustomException) {
            log.warn(AspectLogUtils.buildLog(joinPoint, e.getMessage()).toString());
            throw new ServiceException(((BizCustomException) e).getMessageEnum(), e);
        }

        // C类异常直接返回
        if (e instanceof DaoException) {
            return;
        }

        //  自定义Service异常(手动抛出，记录请求信息、简单异常信息),日志级别warn
        if (log.isWarnEnabled() && e instanceof ServiceException) {
            log.warn(AspectLogUtils.buildLog(joinPoint, e.getMessage()).toString());
            return;
        }

        // 程序运行异常，记录请求信息、异常堆栈信息，日志级别error,封装ServiceException重新抛出
        if (log.isErrorEnabled()) {
            log.error(AspectLogUtils.buildLog(joinPoint, e).toString());
            throw new ServiceException(ErrorCode.B0001, e);
        }
    }
}
